package com.sxt.realm;

import com.sxt.common.ActiveUser;
import com.sxt.domain.User;
import com.sxt.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }


    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名
        String username=authenticationToken.getPrincipal().toString();
        //根据登陆名查询用户对象
        User user=userService.queryUserByLoginName(username);
        if(null!=user){
            ActiveUser activeUser=new ActiveUser();
            activeUser.setUser(user);
            /**
             * 参数说 明
             * principal:向doGetAuthorizationInfo方法和subject.getPrincipal();返回一个对象
             * credentials:用户密码的密文
             * realmName:当前自定义Realem类的名称  我们这里是重写getName方法得到
             */
//            AuthenticationInfo info=new SimpleAuthenticationInfo(activeUser,user.getPassword(),this.getName());

            ByteSource credentialsSalt=ByteSource.Util.bytes(user.getName());//盐
            /**
             * 参数说
             * 参数1：向doGetAuthorizationInfo方法和subject.getPrincipal();返回一个对象
             * 参数2：数据库里面存放的加密的密文
             * 参数3:盐
             * 参数4：当前realm的名字
             */
            AuthenticationInfo info=new SimpleAuthenticationInfo(activeUser,user.getPwd(),credentialsSalt,this.getName());

            return info;

        }else{
            return null; //用户不存在
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       return null;
    }
}
